package scatter.wxmp.rest.security;

import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 自定义一个provide目前主要为了微信登录
 * Created by yangwei
 * Created at 2020/7/28 13:37
 */

public class WxMpCodeAuthenticationProvider extends DaoAuthenticationProvider {

    private WxMpService wxMpService;

    @Override
    public boolean supports(Class<?> authentication) {
        return (WxMpCodeAuthenticationToken.class
                .isAssignableFrom(authentication));
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String appId = authentication.getPrincipal().toString();
        String code = authentication.getCredentials().toString();
        wxMpService.switchover(appId);
        // 偷梁换柱 这里把两个交换一下,因为我们后台userDetailsService是根据userName
        WxMpCodeAuthenticationToken wxMpCodeAuthenticationToken = new WxMpCodeAuthenticationToken(code, appId);
        return super.authenticate(wxMpCodeAuthenticationToken);
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        // 不需要额外验证 主要是去除密码验证
    }

    public void setWxMpService(WxMpService wxMpService) {
        this.wxMpService = wxMpService;
    }
}
